<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['user_id']) 
			&& isset($_GET['year']) && isset($_GET['week'])) {
	require_once 'db.inc.php';
	echo json_encode(getShifts($_GET['user_id'], $_GET['year'], $_GET['week']));
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$data = file_get_contents("php://input");
	if ($data == null) {
		header("HTTP/1.1 400 Bad Request");
		exit;
	}
	
	$data = json_decode($data, true);
	require_once 'db.inc.php';
	require_once 'gcm.send.php';
	print_r($data);
	updateShifts($_GET['user_id'], $data, $_GET['origin']);
}  else {
	header("HTTP/1.1 400 Bad Request");
}

function getShifts($user_id, $year, $week) {
	
	//	echo sprintf("SELECT * FROM shifts WHERE user = %d AND year = %d AND week = %d",
	//			$_GET['user_id'], $_GET["year"], $_GET["week"]);
	$result = mysql_query(sprintf("SELECT * FROM ".TABLE_PREFIX."shifts WHERE user = %d AND year = %d AND week = %d",
			$user_id, $year, $week)) or die(mysql_error());
	$shifts = array();
	while ($row = mysql_fetch_assoc($result)) {
		$shifts[] = array(
				"year" => $row['year'],
				"week" => $row['week'],
				"day" => $row['day'],
				"start" => $row['start'],
				"end" => $row['end']
		);
	}
	return $shifts;
}

function getShifts($user_id, $start_week = 0, $end_week = 106600) {
	$shifts = array();
	
	return $shifts;
}

function updateShifts($user_id, $data, $origin) {
	$week_years = array();
	foreach ($data as $shift) {
		$week_years[] = $shift['year']."-".$shift['week'];
		if ($shift['type'] === 'add') {
			addShift($user_id, $shift);
		} else if ($shift['type'] === 'delete') {
			deleteShift($user_id, $shift);
		} else if ($shift['type'] === 'edit') {
			editShift($user_id, $shift);
		}
	}
	sendUpdateMessage($_GET['user_id'], array_unique($week_years), $origin);
}

function addShift($user_id, $shift) {
	mysql_query(sprintf("INSERT INTO ".TABLE_PREFIX."shifts (user, year, week, day, start, end) VALUES (%d, %d, %d, %d, %.2f, %.2f)",
			$user_id, $shift['year'], $shift['week'], $shift['day'], $shift['start'], $shift['end']));
}

function deleteShift($user_id, $shift) {
	mysql_query(sprintf("DELETE FROM ".TABLE_PREFIX."shifts WHERE user = %d AND year = %d AND week = %d AND day = %d AND start = %.2f AND end = %.2f",
			$user_id, $shift['year'], $shift['week'], $shift['day'], $shift['start'], $shift['end']));
}

function editShift($user_id, $shift) {
	mysql_query(sprintf("UPDATE ".TABLE_PREFIX."shifts SET start = %.2f, end = %.2f WHERE user = %d AND year = %d AND week = %d AND day = %d AND start = %.2f AND end = %.2f",
			$shift['start'], $shift['end'], $user_id, $shift['year'], $shift['week'], $shift['day'], $shift['prev_start'], $shift['prev_end'])) or die(mysql_error());
}
?>